package com.fengye.security.captcha.authentication.security.config;

import com.fengye.security.captcha.authentication.security.beans.MyAuthenticationFailureHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationDetailsSource;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.WebAuthenticationDetails;

import javax.servlet.http.HttpServletRequest;

/**
 *
 * @author sky
 * @date 2021年06月01日 11:49 上午
 */
@EnableWebSecurity
public class MyWebSecurityConfigure extends WebSecurityConfigurerAdapter {

    @Autowired
    private AuthenticationDetailsSource<HttpServletRequest, WebAuthenticationDetails> myAuthenticationDetailsSource;

    @Autowired
    private AuthenticationProvider authenticationProvider;



    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        // 应用 AuthenticationProvider
        auth.authenticationProvider(authenticationProvider);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/admin/api/**").hasAnyAuthority("ROLE_ADMIN") // 必须拥有"ROLE_ADMIN"的权限
                .antMatchers("/user/api/**").hasRole("USER") // 必须拥有"USER"的角色
                .antMatchers("/app/api/**", "/captcha.jpg").permitAll() // 不需要认证
                .anyRequest().authenticated() // 其他的端点都必须登录认证
                .and()
                .csrf().disable() // 关闭 csrf 校验
                .formLogin()// 开启 form 登录
                .authenticationDetailsSource(myAuthenticationDetailsSource)
                .loginPage("/myLogin.html")
                .loginProcessingUrl("/auth/form")
                .permitAll()
                .failureHandler(new MyAuthenticationFailureHandler())
        ;
    }
}
